﻿Imports Windows.Phone.PersonalInformation
Imports System.Threading.Tasks
Imports System.Collections.ObjectModel

Namespace Utility
    Public Module RemoteIdHelper
        Private Const ContactStoreLocalInstanceIdKey As String = "LocalInstanceId"

        Public Async Function SetRemoteIdGuid(store As ContactStore) As Task
            Dim properties As IDictionary(Of String, Object)
            properties = Await store.LoadExtendedPropertiesAsync
            If Not properties.ContainsKey(ContactStoreLocalInstanceIdKey) Then
                ' the given store does not have a local instance id so set one against store extended properties
                Dim g = Guid.NewGuid()
                properties.Add(ContactStoreLocalInstanceIdKey, g.ToString())
                Dim readonlyProperties As New ReadOnlyDictionary(Of String, Object)(properties)
                Await store.SaveExtendedPropertiesAsync(readonlyProperties)
            End If
        End Function

        Public Async Function GetTaggedRemoteId(store As ContactStore, remoteId As String) As Task(Of String)
            Dim taggedRemoteId As String = String.Empty

            Dim properties As IDictionary(Of String, Object)
            properties = Await store.LoadExtendedPropertiesAsync
            If properties.ContainsKey(ContactStoreLocalInstanceIdKey) Then
                taggedRemoteId = String.Format("{0}_{1}", properties(ContactStoreLocalInstanceIdKey), remoteId)
            End If

            Return taggedRemoteId
        End Function

        Public Async Function GetUntaggedRemoteId(store As ContactStore, taggedRemoteId As String) As Task(Of String)
            Dim remoteId As String = String.Empty

            Dim properties As IDictionary(Of String, Object)
            properties = Await store.LoadExtendedPropertiesAsync
            If properties.ContainsKey(ContactStoreLocalInstanceIdKey) Then
                Dim localInstanceId As String = TryCast(properties(ContactStoreLocalInstanceIdKey), String)
                If taggedRemoteId.Length > localInstanceId.Length + 1 Then
                    remoteId = taggedRemoteId.Substring(localInstanceId.Length + 1)
                End If
            End If

            Return remoteId
        End Function
    End Module
End Namespace